package com.bwie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.mapper.TbRoleMapper;
import com.bwie.pojo.TbRole;
import com.bwie.pojo.TbUser;
import com.bwie.service.TbUserService;
import com.bwie.mapper.TbUserMapper;
import com.bwie.utils.R;
import com.bwie.vo.LoginInfoVo;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
* @author 18229
* @description 针对表【tb_user】的数据库操作Service实现
* @createDate 2025-04-17 09:33:17
*/
@Service
public class TbUserServiceImpl extends ServiceImpl<TbUserMapper, TbUser>
    implements TbUserService{

    @Autowired
    private TbUserMapper tbUserMapper;

    @Autowired
    TbRoleMapper tbRoleMapper;

    @Autowired
    StringRedisTemplate stringRedisTemplate;


    @Override
    public R login(LoginInfoVo loginInfoVo) {
        TbUser tbUser = tbUserMapper.selectOne(new QueryWrapper<TbUser>().lambda().eq(TbUser::getUserName, loginInfoVo.getUserName()));
        if(tbUser==null){
            return R.ERROR(500,"用户不存在");
        }
        if(!tbUser.getUserPass().equals(loginInfoVo.getUserPass())){

          return R.ERROR(500,"密码错误");
        }

        TbRole tbRole = tbRoleMapper.selectOne(new QueryWrapper<TbRole>().lambda().eq(TbRole::getRoleId, tbUser.getRoleId()));
        if(tbRole==null){
            return R.ERROR(500,"用户没有权限登录");
        }

        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "123456").claim("userId", tbUser.getUserId()).compact();
        String tokenKey="token-"+tbUser.getUserId();
        //将token存入redis中，并设置过期时间为5分钟
        stringRedisTemplate.opsForValue().set(tokenKey,token,5, TimeUnit.MINUTES);
        tbUser.setToken(token);

        return R.OK(tbUser);

    }

    @Override
    public R getUserById(Integer userId) {
        TbUser tbUser = tbUserMapper.selectById(userId);
        return R.OK(tbUser);
    }
}




